package com.scheduled;

import com.gavel.utils.StringUtils;
import com.mrobuy.jdvc.dao.CommonDao;
import com.mrobuy.jdvc.entity.VCShelvesItem;
import com.mrobuy.jdvc.entity.VCShelvesTask;
import com.mrobuy.jdvc.service.ShelvesService;
import com.mrobuy.type.ItemState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *  自动上架任务
 *
 */
@Component
public class ShelvesItemPushTask {

    private static Logger LOG = LoggerFactory.getLogger(ShelvesItemPushTask.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private CommonDao commonDao;

    @Autowired
    private ShelvesService shelvesService;

    @Scheduled(fixedDelay = 1000*10)
    public void reportCurrentTime() {

        if ( !TaskSwitch.ITEM_PUSH.get() ) {
            return;
        }

        List<VCShelvesTask> tasks = jdbcTemplate.query("select  * from vc_shelves_task where ENABLE = 'Y' order by ENABLETIME", new BeanPropertyRowMapper<>(VCShelvesTask.class));
        if ( tasks==null || tasks.size()==0 ) {
            return;
        }

        for (VCShelvesTask task : tasks) {

            try {
                LOG.info("[SKU上架][Task: {}]", task.getName());
                execTask(task);
            } catch (Exception e) {
                    LOG.error(e.getMessage(), e);
            }
        }

    }

    private void execTask(VCShelvesTask task) {
        if ( task==null || StringUtils.isBlank(task.getId())) {
            return;
        }

        List<VCShelvesItem> items = jdbcTemplate.query("select  * from VC_SHELVES_ITEM where ENABLE = 'Y'  and TASKID = ?  and ZT = ? order by PRODUCTCODE", new BeanPropertyRowMapper<>(VCShelvesItem.class), task.getId(), ItemState.READY.code());
        if ( items==null || items.size()==0 ) {
            return;
        }

        Map<String, List<VCShelvesItem>> map = items.stream().collect(Collectors.groupingBy(VCShelvesItem::getProductcode));

        for (Map.Entry<String, List<VCShelvesItem>> entry : map.entrySet()) {
            LOG.info("\t[上架]{}: {}", entry.getKey(), entry.getValue().size());
           try {
               shelvesService.shelves(entry.getValue());
           } catch (Exception e) {
               LOG.error(e.getMessage(), e);
           }

            for (VCShelvesItem shelvesItem : entry.getValue()) {
                commonDao.update(shelvesItem);
            }
        }
    }
}
